<template>
  <view class="player">
    <ad-unlock-popup1 ref="adUnlockPopup1Ref"></ad-unlock-popup1>
    <ad-unlock-popup2 ref="adUnlockPopup2Ref"></ad-unlock-popup2>
    <pay-popup ref="payPopupRef"></pay-popup>
  </view>
</template>

<script setup lang="ts">
  import AdUnlockPopup1 from '@/components/pay/ad-unlock-popup1/ad-unlock-popup1.vue';
  import AdUnlockPopup2 from '@/components/pay/ad-unlock-popup2/ad-unlock-popup2.vue';
  import { getAppInfo } from '@/config/mp-config';
  import type { TtMpConfig } from '@/config/mp/tt';
  import { RewardedVideoAd } from '@/utils/page/adUtil';
  import { computed, onBeforeMount, onMounted, onUnmounted, ref, shallowRef } from 'vue';
  import { addAdRecordAxios, createDyBalanceOrderAxios, createTtAdvertOrderAxios } from '@/api/pay';
  import PayPopup from '../pay-popup/pay-popup.vue';
  import { useAppStore } from '@/pinia/app';
  import { addChasingDramaAxios, addWatchDramaAxios, cancelChasingDramaAxios } from '@/api/drama';
  import { autoLogin } from '@/utils/page/user';
  import { userActionLog } from '@/api/datapoint';

  const appStore = useAppStore();
  const loginState = computed(() => appStore.loginState);
  const chasingLoading = ref(false);
  const adUnlockPopup1Ref = ref<InstanceType<typeof AdUnlockPopup1>>();
  const adUnlockPopup2Ref = ref<InstanceType<typeof AdUnlockPopup2>>();
  const payPopupRef = ref<InstanceType<typeof PayPopup>>();

  const pm = shallowRef<tt.PlayletManager>();
  let ad: RewardedVideoAd | undefined = undefined;
  onMounted(() => {
    ad = useAd();
    uni.$on('ttOpenAd', () => {
      openAd1Popup();
    });
  });

  onUnmounted(() => {
    ad?.destroy();
    uni.$off('ttOpenAd');
  });

  onBeforeMount(() => {
    pm.value = tt.getPlayletManager({
      is: 'player', // 和插槽同名
    });

    /** 点击控件时触发。返回当前点击的控件类型。取值见表 controlType 的合法值 */
    pm.value.onControlTap((e) => {
      console.log('e', e);
      if (e?.controlType === 'userCloseCharge') {
        openAd1Popup();
      } else if (e?.controlType === 'subscribe') {
        changeChasingDrama('subscribe', e.albumId!);
        //追剧
        userActionLog({
          userId: appStore.userInfo?.userId,
          data: JSON.stringify(e),
          eventType: 'AI_TOUTIAO_WATCH_SUBSCRIBE',
          msg: '',
        });
      } else if (e?.controlType === 'unsubscribe') {
        changeChasingDrama('unsubscribe', e.albumId!);
        //取消追剧
        userActionLog({
          userId: appStore.userInfo?.userId,
          data: JSON.stringify(e),
          eventType: 'AI_TOUTIAO_WATCH_UNSUBSCRIBE',
          msg: '',
        });
      } else if (e?.controlType === 'like') {
        //取消追剧
        userActionLog({
          userId: appStore.userInfo?.userId,
          data: JSON.stringify(e),
          eventType: 'AI_TOUTIAO_WATCH_LIKE',
          msg: '',
        });
      } else if (e?.controlType === 'unlike') {
        //取消追剧
        userActionLog({
          userId: appStore.userInfo?.userId,
          data: JSON.stringify(e),
          eventType: 'AI_TOUTIAO_WATCH_UNLIKE',
          msg: '',
        });
      } else if (e?.controlType === 'share') {
        //取消追剧
        userActionLog({
          userId: appStore.userInfo?.userId,
          data: JSON.stringify(e),
          eventType: 'AI_TOUTIAO_WATCH_SHARE',
          msg: '',
        });
      }
    });

    pm.value.onChangeEpisode((e) => {
      if (e?.status === 'lock') {
        if (appStore.userInfo?.isAutoPay) {
          unlock(e);
        } else {
          openPopup(e);
        }
      }
    });

    pm.value.onClickUnlock((e) => {
      openPopup(e);
    });

    pm.value.onPlay((e) => {
      loginState.value && addWatchDramaAxios({ thirdDramaId: e.albumId, episodeSeq: e.seq });
    });
  });

  /**
   * 通过是否为 AII 判断 显示广告解锁弹出框,还是支付弹出框
   */
  function openPopup(dramaInfo: tt.BaseAlbumInfo | tt.PlayletOnClickUnlock) {
    appStore.isIaaFlag === 1 ? openAd1Popup() : payPopupRef.value?.show({ pm: pm.value!, dramaInfo });
  }

  /** 余额解锁 */
  async function unlock(playletInfo: tt.BaseAlbumInfo) {
    try {
      const res = await createDyBalanceOrderAxios({
        thirdDramaId: playletInfo.albumId,
        episodeSeq: playletInfo.seq,
        referralLinkId: appStore.launchQuery?.referralLinkId,
        channelId: appStore.launchQuery?.channelId,
      });
      appStore.updateVirtualCoins(res.data.virtualCoins);
      if (res.data.unLockStatus === 1) {
        pm.value?.setCurrentUnlock();
      } else {
        openPopup(playletInfo);
      }
    } catch (error) {
      console.log('error====', error);
    }
  }

  /** 追剧 */
  async function changeChasingDrama(type: 'subscribe' | 'unsubscribe', albumId: string) {
    try {
      !loginState.value && (await autoLogin());
      chasingLoading.value = true;
      if (type === 'unsubscribe') {
        await cancelChasingDramaAxios({ thirdDramaId: albumId });
      } else {
        await addChasingDramaAxios({ thirdDramaId: albumId });
      }
      chasingLoading.value = false;
    } catch (error) {
      chasingLoading.value = false;
    }
  }

  /** 打开广告解锁1 弹出框 */
  function openAd1Popup() {
    adUnlockPopup1Ref.value?.show({
      /** 关闭弹出框 */
      closePopup() {
        if (appStore.twoAdvertFrame) {
          openAd2Popup();
        }
      },
      /** 打开广告视频 */
      openAd() {
        console.log('open');
        handleAd();
      },
      /** 关闭弹出框 */
      openPay() {
        pm.value!.getPlayletInfo().then((info) => {
          payPopupRef.value?.show({ pm: pm.value!, dramaInfo: info });
        });
      },
    });
  }

  /** 打开广告解锁2 弹出框 */
  function openAd2Popup() {
    adUnlockPopup2Ref.value?.show({
      /** 打开广告视频 */
      openAd() {
        handleAd();
      },
    });
  }

  /**
   * 广告解锁
   */
  async function handleAd() {
    const _ad = ad?.getAdInstance();
    if (_ad) {
      try {
        uni.showLoading({ mask: true, title: '广告加载中...' });
        await _ad.show();
        uni.hideLoading();
      } catch (error) {
        // 失败一次重试
        try {
          await _ad.load();
          await _ad?.show();
          uni.hideLoading();
        } catch (error2) {
          uni.hideLoading();
          console.log('error====', error2);
          userActionLog({
            userId: appStore.userInfo?.userId,
            data: JSON.stringify(_ad),
            eventType: 'TOUTIAO_AD_LOAD',
            msg: JSON.stringify(error2),
          });
          uni.showToast({ title: '广告加载失败，BD001', icon: 'none', position: 'bottom' });
        }
      }
    } else {
      userActionLog({
        userId: appStore.userInfo?.userId,
        data: JSON.stringify(_ad),
        eventType: 'TOUTIAO_AD_LOAD',
        msg: '',
      });
      uni.showToast({ title: '广告加载失败，BD002', icon: 'none', position: 'bottom' });
    }
  }

  /** 注册广告解锁 */
  function useAd() {
    const appinfo = getAppInfo() as TtMpConfig | undefined;
    const adUnitId = appinfo?.adUnitId || '';
    return new RewardedVideoAd({
      adUnitId,
      /** 广告关闭回调 */
      adCloseCallback: async (data) => {
        if (data.isEnded) {
          const info = await pm.value?.getPlayletInfo();
          try {
            uni.showLoading({ mask: true, title: '解锁中...' });
            const recordRes = await addAdRecordAxios({
              thirdDramaId: info!.albumId!,
              episodeSeq: info!.seq,
              referralLinkId: appStore.launchQuery?.referralLinkId,
              adUnitId,
              promotionId: appStore.launchQuery?.promotionid,
              launchQueryPramas: appStore.newLaunchQuery || {},
            });
            const param = { advertToken: recordRes.data.advertToken, thirdDramaId: info!.albumId!, episodeSeq: info!.seq!, adUnitId };
            const unlockOrderRes = await createTtAdvertOrderAxios(param);
            pm.value?.setCatalog({
              lockList: unlockOrderRes.data.lockList,
              unlockList: unlockOrderRes.data.unlockList,
              freeList: unlockOrderRes.data.freeList,
            });
            uni.hideLoading();
          } catch (error) {
            userActionLog({
              userId: appStore.userInfo?.userId,
              data: JSON.stringify({
                thirdDramaId: info!.albumId!,
                episodeSeq: info!.seq,
                referralLinkId: appStore.launchQuery?.referralLinkId,
              }),
              eventType: 'TOUTIAO_AD_OPEN',
              msg: JSON.stringify(error),
            });
            uni.showToast({ title: error.msg || '广告解锁失败,BD0007', icon: 'none', position: 'bottom' });
            uni.hideLoading();
          }
        } else {
          console.log('广告未看完====');
          openAd2Popup();
        }
      },
    });
  }
</script>

<style>
  .player {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
</style>
